package com.naizhuai.ui.mianbusiness.action;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.naizhuai.R;
import com.naizhuai.network.exception.ApiException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.adapter.ManageDividerItemDecoration;
import com.naizhuai.ui.adapter.business.ActionContractEditAdapterHolder;
import com.naizhuai.ui.adapter.business.ActionContrastImagePagerAdapter;
import com.naizhuai.ui.components.BetterRecyclerView;
import com.naizhuai.ui.components.SpinerPopWindow;
import com.naizhuai.ui.components.listener.PopUpWindowMissListener;
import com.naizhuai.ui.components.listener.PopupItemListener;
import com.naizhuai.ui.components.listener.SpinnerListener;
import com.naizhuai.ui.entity.AnlyParamsBean;
import com.naizhuai.ui.entity.ImageBean;
import com.naizhuai.ui.entity.LabelsConvertBean;
import com.naizhuai.ui.entity.mainbusiness.ActionBaseBean;
import com.naizhuai.ui.entity.mainbusiness.ActionCompareDataBean;
import com.naizhuai.ui.entity.mainbusiness.CompareImageBean;
import com.naizhuai.ui.entity.mainbusiness.ActionEditContractActivityBean;
import com.naizhuai.ui.entity.management.CompanyBean;
import com.naizhuai.ui.mianbusiness.action.presenter.ActionManageApiStoreIml;
import com.naizhuai.ui.mianbusiness.action.presenter.DownloadImageApiStoreIml;
import com.naizhuai.ui.mianbusiness.action.presenter.UploadImageApiStoreIml;
import com.naizhuai.ui.mianbusiness.presenter.PublicDataApiStoreIml;
import com.naizhuai.ui.viewpagerindicator.CirclePageIndicator;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.DeviceUtils;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.ErrorViewCreateUtils;
import com.naizhuai.util.FileNameUtils;
import com.naizhuai.util.IntentUtils;
import com.naizhuai.util.MathUtils;
import com.naizhuai.util.NaizhuAILog;
import com.naizhuai.util.RxBus;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observer;

/**
 * 行为设置页面——设置对比图片以及图片合成
 */
public class ActionEditContrastActivity extends BaseActivity implements ActionContrastImagePagerAdapter.PagerManageImageListener, View.OnClickListener {
    private static final String TAG = "ActionEditContrastActivity";

    @BindView(R.id.pager_indicator)
    MagicIndicator magicIndicator;
    @BindView(R.id.action_contract_list)
    ViewPager contractList;
    private CommonNavigator commonNavigator;
    private List<String> pagerTitle;
    private String[] mergeBaseTitle;
    private List<CompareImageBean> imageEditList;

    //改善
    @BindView(R.id.change_data)
    EditText changeValue;

    //结构体
    @BindView(R.id.pre_compare_data_layout)
    LinearLayout compareData;
    @BindView(R.id.compare_data_label)
    TextView chosenDataLabel;
    @BindView(R.id.after_data_value)
    EditText afDataValue;
    @BindView(R.id.count_type_details)
    EditText countType;
    @BindView(R.id.chosen_equip_item)
    TextView equipTxt;
    @BindView(R.id.equip_chosen_layout)
    LinearLayout equipLayout;

    //行动心得
    @BindView(R.id.add_content)
    EditText addContent;

    private ActionContrastImagePagerAdapter imageEditAdapter;


    private String actionId;

    private final static String VIRTUAL_ACTION_ID = "42";

    private ActionEditContractActivityBean editPagerData;

    @BindView(R.id.content_layout)
    NestedScrollView contentLayout;
    @BindView(R.id.error_content)
    RelativeLayout errorLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBaseData();
        initBaseView();
        requestData();
    }

    private void initErrorLayout() {
        errorLayout.setVisibility(View.VISIBLE);
        errorLayout.removeAllViews();
        errorLayout.addView(ErrorViewCreateUtils.createLoadingView(this));
    }

    private void requestData() {
        showWaitDiaLog();
        ActionManageApiStoreIml.getInstance().getComparePagerMsg(actionId)
                .subscribe(new Observer<ActionEditContractActivityBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        ApiException.showException(e, getActivityContext());
                        contentLayout.setVisibility(View.INVISIBLE);
                        errorLayout.setVisibility(View.VISIBLE);
                        errorLayout.removeAllViews();
                        errorLayout.addView(ErrorViewCreateUtils.createNoNetworkView(getActivityContext(), v -> {
                            initErrorLayout();
                            requestData();
                        }));
                    }

                    @Override
                    public void onNext(ActionEditContractActivityBean actionEditPagerBean) {
                        hideWaitDialog();
                        contentLayout.setVisibility(View.VISIBLE);
                        errorLayout.setVisibility(View.GONE);
                        NaizhuAILog.e("actionEditPagerBean=" + actionEditPagerBean.toString());
                        editPagerData = actionEditPagerBean;
                        NaizhuAILog.e("editPagerData.getProcessImgs=" + Arrays.toString(editPagerData.getProcessImages().toArray()));
                        changeValue.setText(editPagerData.getSchemeName());
                        if (editPagerData.getSelectedCompareData() != null && editPagerData.getSelectedCompareData().size() > 0 && !TextUtils.isEmpty(editPagerData.getSelectedCompareData().get(0).getPointId())) {
                            compareData.setVisibility(View.VISIBLE);
                            ActionCompareDataBean compareBean = editPagerData.getSelectedCompareData().get(0);
                            chosenDataLabel.setText(String.format("%s.%s", compareBean.getPointName(), compareBean.getEnteringName()));
                            afDataValue.setText(compareBean.getaValue());
                            countType.setText(compareBean.getaFormula());
                            if (!TextUtils.isEmpty(compareBean.getMachineName())) {
                                equipLayout.setVisibility(View.VISIBLE);
                                afDataValue.setGravity(Gravity.END);
                                equipTxt.setText(compareBean.getMachineName());
                            } else {
                                afDataValue.setGravity(Gravity.CENTER);
                                equipLayout.setVisibility(View.GONE);
                            }
                        } else
                            compareData.setVisibility(View.GONE);

                        addContent.setText(editPagerData.getReview());
                        imageEditList.clear();
                        imageEditList.addAll(editPagerData.getCompareImage());
                        pagerTitle.clear();
                        pagerTitle.addAll(Arrays.asList(mergeBaseTitle).subList(0, imageEditList.size()));
                        commonNavigator.notifyDataSetChanged();
                        imageEditAdapter.notifyDataSetChanged();
                        getImageResources(imageEditList);
                    }
                });

    }

    private void getImageResources(List<CompareImageBean> imageEditList) {
        for (int index = 0; index < imageEditList.size(); index++) {
            ImageBean before = imageEditList.get(index).getBeforeImage();
            ImageBean after = imageEditList.get(index).getAfterImage();
            setImageItemUri(before, index);
            setImageItemUri(after, index);
        }
    }

    private void setImageItemUri(ImageBean bean, int position) {
        if (bean == null)
            return;
        AnlyParamsBean<File> fileAnly = FileNameUtils.isExistFileByName(this, bean.getPath());
        if (fileAnly.isHas()) {
            Uri fileUri = Uri.fromFile(fileAnly.getThing());
            bean.setImageUriInput(fileUri);
            imageEditList.get(position).setBeforeImage(bean);
            bean.setImageUriOutput(FileNameUtils.getCacheUri(bean.getPath(), ActionEditContrastActivity.this));
            NaizhuAILog.e(" imageEditList.get(Index)=" + imageEditList.get(position).toString());
            imageEditAdapter.notifyDataSetChanged();
        } else {
            DownloadImageApiStoreIml.getInstance().downloadImageByUrl(bean.getUrl(),
                    FileNameUtils.createFileNamePath(this, bean.getPath(), FileNameUtils.NOT_CACHE_FILE))
                    .subscribe(new Observer<File>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            ApiException.showException(e, getActivityContext(), true);
                            NaizhuAILog.e("ThrowableOnError e=" + e.getMessage());
                        }

                        @Override
                        public void onNext(File file) {
                            NaizhuAILog.e(" imageEditList.get(finalIndex)=" + imageEditList.get(position).toString());
                            bean.setImageUriInput(FileNameUtils.file2Uri(ActionEditContrastActivity.this, file));
                            bean.setImageUriOutput(FileNameUtils.getCacheUri(file.getName(), ActionEditContrastActivity.this));
                            imageEditList.get(position).setBeforeImage(bean);
                            imageEditAdapter.notifyDataSetChanged();
                        }
                    });
        }
    }

    private void initBaseData() {
        imageEditList = new ArrayList<>();
        pagerTitle = new ArrayList<>();
        mergeBaseTitle = getResources().getStringArray(R.array.action_merge_image_list_title);
        Bundle dataBundle = getIntent().getExtras();
        if (dataBundle != null) {
            actionId = dataBundle.getString(ActionBaseBean.ACTION_ID_KEY);
        } else
            actionId = VIRTUAL_ACTION_ID;

    }

    private void initBaseView() {
        chosenDataLabel.setText(getText(R.string.virtual_data_source).toString());
        initRecyclerView();
    }


    private void initRecyclerView() {
        imageEditAdapter = new ActionContrastImagePagerAdapter(this, imageEditList, this);
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                contractList.getLayoutParams().height = DeviceUtils.getScreenDevice(ActionEditContrastActivity.this)[0];
                contractList.setAdapter(imageEditAdapter);
                contractList.setOffscreenPageLimit(5);
                initIndicator();
            }
        });
    }

    private void initIndicator() {
        magicIndicator.setBackgroundColor(Color.WHITE);
        commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return pagerTitle.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorTransitionPagerTitleView(context);
                simplePagerTitleView.setNormalColor(Color.GRAY);
                simplePagerTitleView.setSelectedColor(Color.BLACK);
                simplePagerTitleView.setText(pagerTitle.get(index));
                simplePagerTitleView.setTextSize(13);
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        contractList.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
                linePagerIndicator.setColors(ContextCompat.getColor(ActionEditContrastActivity.this, R.color.tab_blue));
                return linePagerIndicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator, contractList);
    }


    @OnClick({R.id.back_icon, R.id.pre_step, R.id.next_step})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_icon:
                onBackPressed();
                break;
            case R.id.pre_step:
                //上一步
                IntentUtils.startActivityWithString(new String[]{ActionBaseBean.ACTION_ID_KEY, IntentUtils.ENTER_ACTIVITY_TYPE_KEY},
                        new String[]{actionId, String.valueOf(IntentUtils.PREVIEW_FROM_SCAN)}, this, ActionDetailTxtCreateActivity.class);
                finish();
                break;
            case R.id.next_step:
                //下一步
                submitScanPager();
                break;
        }
    }

    @Override
    public void onBackPressedWithoutDialog() {
        DialogUtils.showSureDialog(this, getString(R.string.lost_data), new View.OnClickListener() {
            @Override
            public void onClick(View dialog) {
                finish();
            }
        });
    }

    private void submitScanPager() {
        showWaitDiaLog();
        editPagerData.setSchemeName(changeValue.getText().toString());
        editPagerData.setQuestionId(actionId);
        editPagerData.setReview(addContent.getText().toString());
        if (editPagerData.getSelectedCompareData() != null && editPagerData.getSelectedCompareData().size() > 0 && !TextUtils.isEmpty(editPagerData.getSelectedCompareData().get(0).getPointId())) {
            ActionCompareDataBean dataBean = editPagerData.getSelectedCompareData().get(0);
            if (TextUtils.isEmpty(afDataValue.getText().toString()))
                DialogUtils.showPromptDialog(this, getText(R.string.data_message_is_not_finished).toString());
            else {
                if (MathUtils.parseStringToDouble(afDataValue.getText().toString()) == -1) {
                    DialogUtils.showPromptDialog(getActivityContext(), getString(R.string.number_data_error));
                    return;
                }
                if (afDataValue.getText().toString().equals("0")) {
                    DialogUtils.showSureDialog(this, getString(R.string.after_number_zero), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dataBean.setaValue(afDataValue.getText().toString());
                            dataBean.setaFormula(countType.getText().toString());
                            NaizhuAILog.e("dataBean.getBvalue=" + dataBean.getbValue());
                            editPagerData.setSelectedCompareData(Collections.singletonList(dataBean));
                            imageEditAdapter.cropAndSaveImages();
                        }
                    });
                } else {
                    dataBean.setaValue(afDataValue.getText().toString());
                    dataBean.setaFormula(countType.getText().toString());
                    NaizhuAILog.e("dataBean.getBvalue=" + dataBean.getbValue());
                    editPagerData.setSelectedCompareData(Collections.singletonList(dataBean));
                    imageEditAdapter.cropAndSaveImages();
                }
            }
        } else {
            imageEditAdapter.cropAndSaveImages();
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_business_action_edit_constrast_layout;
    }

    @Override
    protected void onDestroy() {
        imageEditAdapter.stopCropVIew();
        super.onDestroy();
    }

    @Override
    public void uploadImage(ImageBean s, int position) {
        NaizhuAILog.e("uploadImage");
        imageEditList.get(position).setAfterImage(s);
    }

    @Override
    public void emptyImageError() {
        hideWaitDialog();
        shortToast(getString(R.string.gestview_is_empty));
    }

    @Override
    public void downloadImageError(Throwable e) {

    }

    @Override
    public void onLoadTransComplete() {

    }

    @Override
    public void onLoadTransFailure(@NonNull Exception e) {

    }

    @Override
    public void onTransRotate(float currentAngle) {

    }

    @Override
    public void onTransScale(float currentScale) {

    }

    @Override
    public void cropImage(Uri cropUri, int position, String cropPosition) {
        if (cropPosition.equals(ActionContractEditAdapterHolder.AFT_GES_VIEW_KEY))
            imageEditList.get(position).getAfterImage().setImageUriOutput(cropUri);
        else if (cropPosition.equals(ActionContractEditAdapterHolder.PRE_GES_VIEW_KEY))
            imageEditList.get(position).getBeforeImage().setImageUriOutput(cropUri);
    }

    @Override
    public void cropImagesFinished() {
        hideWaitDialog();
        editPagerData.setCompareImage(imageEditList);
        RxBus.getDefault().postSticky(editPagerData);
        shortToast("合成完成");
        IntentUtils.startActivity(this, ActionScanDetailsViewActivity.class);
    }

    @Override
    public void cropImageErrer(Throwable t, int position) {
        NaizhuAILog.e("Throwable t=" + t.getMessage());
        hideWaitDialog();
        shortToast("合成失败");
    }

    @Override
    public void loadWrongFile(String wrongType) {
        shortToast(String.format(getText(R.string.load_wrong_file_type).toString(), wrongType));
    }
}
